package com.zhengke.controller;

import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.zhengke.common.util.*;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.zhengke.common.BaseController;
import com.zhengke.common.object.AjaxDone;
import com.zhengke.common.object.ZTreeNode;
import com.zhengke.pojo.MallGoodsClass;
import com.zhengke.service.GoodsClassService;

@Controller
@RequestMapping("goodsClass")
public class GoodsClassController extends BaseController {

    @Autowired
    private GoodsClassService service;

    /**
     * 到商品分类页面
     *
     * @return
     */
    @RequestMapping("toMgr.do")
    public String query() {
        return "goodsClass/goodsClassMgr";
    }

    /**
     * 商品分类树
     *
     * @param id 返回数据字典的Json格式数据
     */
    @ResponseBody
    @RequestMapping("tree.do")
    public List<ZTreeNode> tree(String id) {
        List<ZTreeNode> list = new ArrayList<ZTreeNode>();
        if (id != null) {
            list = service.queryParent(id);
            return list;
        }
        list = service.queryParent("0");
        return list;
    }

    /**
     * @return 到修改商品分类页面
     */
    @RequestMapping("toGcUpd.do")
    public String toUpdGoodsClass(String gcId, HttpServletRequest request, ModelMap model) {
        try {
            MallGoodsClass mgc = service.queryById(Integer.parseInt(gcId));
            //model.addAttribute(mgc);
            model.addAttribute("mgc", mgc);

            String picPath = mgc.getGcPicpath();
            if (picPath == null || "".equals(picPath))
                model.put("gcPicPath", request.getSession().getServletContext().getRealPath("/images/") + "/noPic.png");
            else
                model.put("gcPicPath", mgc.getGcPicpath());

            String imgW = LoadProperties.findValue("imgW");
            String imgH = LoadProperties.findValue("imgH");
            model.put("imgW", imgW);
            model.put("imgH", imgH);
            //读取config.properties查找访问路径的ip+端口
            String fileServerUrl = LoadProperties.findValue("FILE_SERVER_URL");
            model.put("fileServerUrl", fileServerUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "goodsClass/toGcUpd";
    }

    /**
     * 删除商品分类信息
     *
     * @param gcId
     * @return
     */
    @ResponseBody
    @RequestMapping("deleteClass.do")
    public AjaxDone deleteGcClass(String gcId) {
        try {
            int rst = service.deleteById(Integer.parseInt(gcId));
            if (rst == -1) {
                return new AjaxDone("300", "该商品分类有子分类,请先删除其子分类!");
            }
            if (rst >= 0) {
                return new AjaxDone("200", "删除成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxDone("300", "系统繁忙,请稍后重试!");
    }

    /**
     * 上传原始图片
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("uploadImage.do")
    public AjaxDone updateImage(@RequestParam("image") CommonsMultipartFile image) {
        try {
            String imageFileName = image.getOriginalFilename();

            if (imageFileName.indexOf(".jpg") == -1
                    && imageFileName.indexOf(".gif") == -1
                    && imageFileName.indexOf(".png") == -1
                    && imageFileName.indexOf(".jpeg") == -1) {
                return new AjaxDone("300", "文件格式不正确，请上传 *.png,*.jpeg,*.gif,*.jpg类型图片");
            }

            String extName = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
            if (image != null && !image.isEmpty()) {
                String path = LoadProperties.findValue("imgPath") + "/" + DateUtil.getSystemDateTimeByFormat("yyyyMMddHHmmss") + "." + extName;
                File file = new File(path);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                FileUtils.copyInputStreamToFile(image.getInputStream(), file);
                String rtnPath = LoadProperties.findValue("viewUrl") + "?path=" + file.getPath();

                return new AjaxDone("200", "上传成功", rtnPath, path);
            } else {
                return new AjaxDone("300", "文件格式不正确，请上传 *.png,*.jpeg,*.gif,*.jpg类型图片");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxDone("300", "上传失败");
    }

    /**
     * 上传剪切后的图片
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("uploadCanvas.do")
    public AjaxDone updateConvars(String gcId, String canvasData, String delFile) {

        try {
            String path = LoadProperties.findValue("imgPath") + "/";
            String fileName = DateUtil.getSystemDateTimeByFormat("yyyyMMddHHmmss") + ".jpg";

            File file = Base64ToImage.decodeBase64ToImage(canvasData, path, fileName);

            //删除原图片
            File delete = new File(delFile);
            if (delete != null) {
                delete.delete();
            }

            if (file != null) {
                String imgW = LoadProperties.findValue("imgW");
                String imgH = LoadProperties.findValue("imgH");
                //保存canvas转成的缩略图
                String filePath = ImageUtil.thumbnailImage(file.getPath(), Integer.parseInt(imgW), Integer.parseInt(imgH), true);
                //删除canvas原图
                file.delete();

                /*
                fastDFS操作
                 */
                //获取文件的扩展名
                String filename = fileName;
                //获取文件后缀名 从最后一个点后一位截取
                String extName = fileName.substring(filename.lastIndexOf(".") + 1);
                //上传fastDFS后图片完整地址
                String file_id = FastDfsApiOpr.upload(filePath, extName);
                //读取config.properties查找访问路径的ip+端口
                String fileServerUrl = LoadProperties.findValue("FILE_SERVER_URL");
                String rtPath = fileServerUrl + file_id;
                System.out.println(file_id);
                System.out.println(fileServerUrl);
                //删除剪切后的本地图片
                File delCanvas = new File(filePath);
                if (delCanvas != null) {
                    delCanvas.delete();
                }

                return new AjaxDone("200", "上传成功!", rtPath, file_id);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxDone("300", "系统繁忙,请稍后重试!");
    }

    /**
     * 保存商品分类信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("updateGoodsClass.do")
    public AjaxDone saveGoodsClass(Integer gcId, String gcName, Short gcSort, String gcDescription, String gcPicpath, String fileId) {
        try {

            //读取config.properties查找访问路径的ip+端口
            String fileServerUrl = LoadProperties.findValue("FILE_SERVER_URL");
            gcPicpath = gcPicpath.replace(fileServerUrl, "");
            fileId = fileId.replace(fileServerUrl, "");
            MallGoodsClass mgc = new MallGoodsClass();
            mgc.setGcId(gcId);
            mgc.setGcName(gcName);
            mgc.setGcSort(gcSort);
            mgc.setGcDescription(gcDescription);
            mgc.setGcPicpath(gcPicpath);

            /*
            保存修改信息
             */
            int rst = service.update(mgc);
            if (rst > 0) {//修改成功
                /**
                 * 删除已经之前上传到服务器的图片，节省存储资源
                 */
                if (!fileId.equals(gcPicpath)) {
                    FastDfsApiOpr.deleteFile(fileId);
                }

                Map<String, String> rtnMap = new HashMap<String, String>();
                rtnMap.put("gcName", mgc.getGcName());
                return new AjaxDone("200", "保存成功!", "", rtnMap);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxDone("300", "系统繁忙,请稍后重试!");
    }

    /**
     * 新增父级商品分类
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("addParentClass.do")
    public AjaxDone addParentClass() {
        MallGoodsClass mgc = new MallGoodsClass();
        mgc.setGcName("新增分类");
        mgc.setGcParentId(0);
        mgc.setGcSort((short) 255);

        try {
            int rst = service.insert(mgc);
            if (rst > 0)
                return new AjaxDone("200", "添加父级分类成功!", "", mgc);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxDone("300", "系统繁忙,请稍后重试!");
    }

    /**
     * 添加子级分类
     *
     * @param gcId
     * @param treeNodeLevel
     * @return
     */
    @ResponseBody
    @RequestMapping("addSubClass.do")
    public AjaxDone addSubClass(String gcId, String treeNodeLevel) {
        if ("2".equals(treeNodeLevel)) {
            return new AjaxDone("300", "最多创建三级商品分类!");
        }
        MallGoodsClass mgc = new MallGoodsClass();
        mgc.setGcName("新增下级分类");
        mgc.setGcParentId(Integer.parseInt(gcId));
        mgc.setGcSort((short) 255);
        try {
            int rst = service.insert(mgc);
            if (rst > 0)
                return new AjaxDone("200", "添加子级分类成功", "", mgc);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxDone("300", "系统繁忙,请稍后重试!");
    }

}
